package fun.yegang.web.controller;

import fun.yegang.utils.UserUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController {

    @GetMapping(value = "test")
    public String test() {
        return UserUtils.getUserFromOauth2();
    }

    @GetMapping(value = "/")
    public String index() {
        return "Welcome ";
    }

    @GetMapping("/isLoggedIn")
    public String isLoggedIn() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null && authentication.isAuthenticated()) {
            return "User is logged in";
        } else {
            return "User is not logged in";
        }
    }

    @GetMapping("/test2")
    public String test2(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
                        @AuthenticationPrincipal OAuth2User oauth2User) {
        System.out.printf("userName:" + oauth2User.getName());
        System.out.printf("clientName:"+ authorizedClient.getClientRegistration().getClientName());
        System.out.printf("userAttributes:"+ oauth2User.getAttributes());
        return "index";
    }
}
